package com.shuo.set;

import java.util.Set;
import java.util.TreeSet;

/**
 * 1. TreeSet底层仅仅是用TreeMap做了代理, put就是treeMap.put(value, FINAL_OBJECT) #FINAL_OBJECT为单例
 * 2. 如果初始化时没传入Comparator, 则add的对象必须实现了Comparable, 不然会抛异常; 详细见Treemap#put,
 * 3. TreeSet里面的元素遍历时会按Comparator或Comparable排序
 */
public class TreeSetTest {
    private static class User implements Comparable {
        private int age;
        private String name;

        public User(int age, String name) {
            this.age = age;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }

        @Override
        public int compareTo(Object o) {
            return (this.age - ((User) o).age);
        }
    }

    public static void main(String[] args) {
        Set set = new TreeSet();
        set.add(new User(22, "Sam"));
        set.add(new User(12, "Tom"));
        set.add(new User(12, "Tonny"));
        set.add(new User(13, "Jenny"));
        for (Object o : set) {
            System.out.println(o);
        }
    }
}
